package com.jwb.pub.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.service.AttachFileDetailService;
import com.jwb.pub.service.importService;
import com.jwb.util.MainController;
import com.jwb.util.ToolsUtil;
@Slf4j
@Controller
@RequestMapping("/pub/import")
public class ImportController extends MainController{
	

	@Autowired
	private importService importService;
	
	@Autowired
	private AttachFileDetailService attachFileDetailService;
	
	@RequestMapping("/list")
	@ResponseBody
	public String list(HttpServletRequest req) throws Exception{
		JSONObject jsobject = new JSONObject();
		String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
		try{
			JSONObject jsdata=JSONObject.parseObject(jsonStr);
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));
			jsobject = importService.list(jsdata, page);			
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取导入列表失败");
		}
		log.info("list(jsonStr="+jsonStr+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	@RequestMapping("/tableinfo")
	@ResponseBody
	public String tableInfo(HttpServletRequest req) throws Exception{
		JSONObject jsobject = new JSONObject();
    	String tableId= req.getParameter("tableId") == null ? "1" : req.getParameter("tableId");
    	String tableName = req.getParameter("tableName") == null ? "-1" : req.getParameter("tableName");
		try{
			JSONObject jsdata = new JSONObject();
			if("-1".equals(tableName)){
				jsdata.put("tableId", tableId);
			}else{
				jsdata.put("tableName", tableName);
			}			
			jsobject = importService.tableInfo(jsdata);			
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取table数据失败");
		}
		log.info("tableinfo(tableId="+tableId+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	@RequestMapping("/upload")
	@ResponseBody
	public String uploadSave(HttpServletRequest req, @RequestParam(value="file")MultipartFile file) throws Exception{
		HttpSession session = req.getSession();
    	String userId = (String) session.getAttribute("userId") == null ? ""
				: (String) session.getAttribute("userId");
    	String tableId = req.getParameter("tableId") == null ? "1" : req.getParameter("tableId");
    	String fileName = req.getParameter("fileName") == null ? "" : req.getParameter("fileName");
		String modeName = req.getParameter("modeName") == null ? "" : req.getParameter("modeName");
		String folder = req.getParameter("folder") == null ? "" : req.getParameter("folder");
		String operCode = req.getParameter("operCode") == null ? userId : req.getParameter("operCode");
		String fileNo = req.getParameter("fileNo") == null ? ToolsUtil.get32bituuid() : req.getParameter("fileNo");
		String fileType = req.getParameter("fileType") == null ? "" : req.getParameter("fileType");
		String fileSize = req.getParameter("fileSize") == null ? "0" : req.getParameter("fileSize");
    	JSONObject jsobject = new JSONObject();
    	try{
    		String rootPath = req.getServletContext().getRealPath("/");
			if (file != null)
			{
				String path = rootPath+folder;	
				String fileExt="";
				try
				{
					fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				String fileId=ToolsUtil.get32bituuid();
				String saveName = fileId + fileExt;
				String filePath = path + "/" + saveName;
				File dir = new File(path);
				if(!dir.exists()) dir.mkdirs();
				InputStream fis = file.getInputStream();
				FileOutputStream fos = new FileOutputStream(filePath);
				
				try
				{
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = fis.read(b)) > 0)
					{
						fos.write(b, 0, len);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					fis.close();
					fos.close();
				}			
			
				jsobject=attachFileDetailService.uploadSingle( operCode, modeName,
						 fileNo, fileId,   folder+"/"+saveName,  fileName,
						 fileType,  fileSize,  fileExt);
			    
				if("0".equals(jsobject.getString("respCode"))){
					JSONObject jsdata = new JSONObject();
					jsdata.put("root", rootPath);
					jsdata.put("path", folder+"/"+saveName);
					jsdata.put("filepath", filePath);
					jsdata.put("tableId", tableId);
					jsdata.put("oper_code", userId);
					jsdata.put("filename", fileName);
					jsdata.put("import_status", "import_status_1");
					jsdata.put("import_check_status", "import_check_status_1");
					jsobject = importService.saveUpload(jsdata);					
				}		
			}
			else
			{
				jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "请选择上传文件");
			}     		
			
		}catch(Exception e){  
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "上传失败");
		}		
    	log.info("upload(fileName="+fileName+",tableId="+tableId+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public String del(HttpServletRequest req, String jsonStr){
		JSONObject jsobject = new JSONObject();
		try{
			JSONObject jsdata = JSONObject.parseObject(jsonStr);	
			jsdata.put("root", req.getServletContext().getRealPath("/"));
			jsobject = importService.del(jsdata);
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "删除失败");
		}		
		log.info("del(jsonStr="+jsonStr+") "+ jsobject.toString());
		return jsobject.toString();
	}
	   /**
	    * 迁移导入数据，导入到正式表
	    * @param req
	    * @return
	    * @throws Exception
	    */
	   	@RequestMapping(value="/subImportData")    
	    @ResponseBody
	    public String  subImportData(HttpServletRequest req,String jsonStr) throws Exception {
	   		JSONObject jsobject = new JSONObject();
	   		HttpSession session = req.getSession();
	    	String userId = (String) session.getAttribute("userId") == null ? ""
					: (String) session.getAttribute("userId");
	 		try{
		   		JSONObject jsdata = JSONObject.parseObject(jsonStr);
		   		jsdata.put("opercode", userId);
		 	    jsobject = importService.subImportData(jsdata);
	 		}catch(Exception e){
	 			e.printStackTrace();
	 			jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "迁移数据失败");
	 		}
	      	log.info("subImportData(jsonStr="+jsonStr+") "+ jsobject.toString());
	 		return jsobject.toString();
	 	} 
	   	
	   	@RequestMapping(value="/check")    
	    @ResponseBody
	    public String  check(HttpServletRequest req,String jsonStr) throws Exception {
	   		JSONObject jsobject = new JSONObject();
	   		HttpSession session = req.getSession();
	    	String userId = (String) session.getAttribute("userId") == null ? ""
					: (String) session.getAttribute("userId");
	   		try{
	   			JSONObject jsdata = JSONObject.parseObject(jsonStr);
	   			jsdata.put("opercode", userId);
	   			jsobject = importService.check(jsdata);	   			
	   		}catch(Exception e){
	   			e.printStackTrace();
	   			jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "迁移数据失败");
	   		}   		
	   		log.info("check(jsonStr="+jsonStr+") "+ jsobject.toString());
	    	return jsobject.toString();
	   	}
	   	
	   	
	@RequestMapping("/reload")
	@ResponseBody
	public String reload(HttpServletRequest req, @RequestParam(value="file")MultipartFile file){
		HttpSession session = req.getSession();
    	String userId = (String) session.getAttribute("userId") == null ? ""
				: (String) session.getAttribute("userId");
    	String importId = req.getParameter("importId")==null?"":req.getParameter("importId");
    	String fileurl = req.getParameter("fileurl")==null?"":req.getParameter("fileurl");
    	String tableId = req.getParameter("tableId") == null ? "1" : req.getParameter("tableId");
    	String fileName = req.getParameter("fileName") == null ? "" : req.getParameter("fileName");
		String modeName = req.getParameter("modeName") == null ? "" : req.getParameter("modeName");
		String folder = req.getParameter("folder") == null ? "" : req.getParameter("folder");
		String operCode = req.getParameter("operCode") == null ? userId : req.getParameter("operCode");
		String fileNo = req.getParameter("fileNo") == null ? ToolsUtil.get32bituuid() : req.getParameter("fileNo");
		String fileType = req.getParameter("fileType") == null ? "" : req.getParameter("fileType");
		String fileSize = req.getParameter("fileSize") == null ? "0" : req.getParameter("fileSize");
    	JSONObject jsobject = new JSONObject();
    	try{
    		String rootPath = req.getServletContext().getRealPath("/");
			if (file != null)
			{
				String path = rootPath+folder;	
				String fileExt="";
				try
				{
					fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				String fileId=ToolsUtil.get32bituuid();
				String saveName = fileId + fileExt;
				String filePath = path + "/" + saveName;
				File dir = new File(path);
				if(!dir.exists()) dir.mkdirs();
				InputStream fis = file.getInputStream();
				FileOutputStream fos = new FileOutputStream(filePath);
				
				try
				{
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = fis.read(b)) > 0)
					{
						fos.write(b, 0, len);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					fis.close();
					fos.close();
				}			
			
				jsobject=attachFileDetailService.uploadSingle( operCode, modeName,
						 fileNo, fileId,   folder+"/"+saveName,  fileName,
						 fileType,  fileSize,  fileExt);
				if("0".equals(jsobject.getString("respCode"))){
					JSONObject jsdata = new JSONObject();
					jsdata.put("root", rootPath);
					jsdata.put("importId", importId);
					jsdata.put("fileUrl", fileurl);
					jsdata.put("path", folder+"/"+saveName);
					jsdata.put("filepath", filePath);
					jsdata.put("tableId", tableId);
					jsdata.put("oper_code", userId);
					jsdata.put("filename", fileName);
					jsdata.put("import_status", "import_status_1");
					jsdata.put("import_check_status", "import_check_status_1");
					jsobject = importService.reload(jsdata);	
					
				}		
			}
			else
			{
				jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "请选择上传文件");
			}     		
			
		}catch(Exception e){  
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "上传失败");
		}		
    	log.info("reload(importId="+importId+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	@RequestMapping(value="/detail")    
    @ResponseBody
    public String  detail(HttpServletRequest req,HttpServletResponse response) throws Exception {
		JSONObject jsobject = new JSONObject();
		String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
		try{
			JSONObject jsdata = JSONObject.parseObject(jsonStr);
//			jsdata.put("root", req.getServletContext().getRealPath("/"));
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));
			jsobject = importService.detail(jsdata,page);
			
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取数据失败");
		}		
		log.info("detail(importId="+req.getParameter("importId")+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	@RequestMapping(value="/tablelist")    
    @ResponseBody
	public String tablelist(HttpServletRequest req,HttpServletResponse response){
		JSONObject jsobject = new JSONObject();
		String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
    	try{
			JSONObject jsdata = JSONObject.parseObject(jsonStr);
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));
			jsobject = importService.tablelist(jsdata,page);
			
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取数据失败");
		}		
		log.info("tablelist(jsonStr="+req.getParameter("jsonStr")+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	@RequestMapping(value="/deltable")    
    @ResponseBody
	public String deltable(HttpServletRequest req,HttpServletResponse response){
		JSONObject jsobject = new JSONObject();
    	String tableId = req.getParameter("tableId") == null ? "" : req.getParameter("tableId");
    	if(!StringUtils.isEmpty(tableId)){
    		jsobject = importService.deltable(tableId);
    	}else{
    		jsobject.put("respCode", "-9");
			jsobject.put("respDesc", "请求参数丢失");
    	}    	 	
    	log.info("deltable(tableId="+tableId+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	@RequestMapping(value="/savetable")    
    @ResponseBody
	public String savetable(HttpServletRequest req,String jsonStr){
		JSONObject jsobject = new JSONObject();
		try{
    		JSONObject jsdata = JSONObject.parseObject(jsonStr);
    		jsobject = importService.savetable(jsdata);
			
    	}catch(Exception e){
    		e.printStackTrace();
    		jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "保存配置失败");
    	}
		log.info("savetable(jsonStr="+jsonStr+") "+ jsobject.toString());
		return jsobject.toString();
	}
	
	
	
}
